package com.linkgie.galaxyframework.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MemoryClassLoader extends ClassLoader {

	private final Map<String, byte[]> codes;

	public MemoryClassLoader(Map<String, byte[]> codes, ClassLoader parentClassLoader) {
		super(parentClassLoader);
		this.codes = new ConcurrentHashMap<>(codes);
	}

	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		try {
			return super.findClass(name);
		} catch (ClassNotFoundException e) {
			// try to find class in current cache;
		}
		
		byte[] classBytes = codes.get(name);
		if (null != classBytes) {
			return defineClass(name, classBytes, 0, classBytes.length);
		}
		throw new ClassNotFoundException("Class '" + name + "' is not found!");
	}

	@Override
	public InputStream getResourceAsStream(String name) {
		byte[] resourceBytes = codes.get(name);
		if (null != resourceBytes) {
			new ByteArrayInputStream(resourceBytes);
		}
		return super.getResourceAsStream(name);
	}

}